#include <WiFi.h>
#include <PubSubClient.h>
#include "UTF8ToGB2312.h"

// WiFi网络相关配置
const char* ssid = "wifi";
const char* password = "wifipass";

// MQTT服务器相关配置
const char* mqtt_server = "0.0.0.0";
const int mqtt_port = 1883;
const char* mqtt_topic = "ttshecheng";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
    Serial.begin(9600);

    WiFi.begin(ssid, password);
    while (WiFi.status()!= WL_CONNECTED) {
        delay(1000);
    }

    client.setServer(mqtt_server, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
        if (client.connect("ArduinoClient")) {
            client.subscribe(mqtt_topic);
        } else {
            delay(1000);
        }
    }
}

void callback(char* topic, byte* payload, unsigned int length) {
    String inputText = "";
    for (int i = 0; i < length; i++) {
        inputText += (char)payload[i];
    }

    String gb2312Text = GB.get(inputText);

    unsigned char headOfFrame[5];
    int length_gb2312 = gb2312Text.length();
    unsigned char ecc = 0;
    int i;

    headOfFrame[0] = 0xFD;
    headOfFrame[1] = 0x00;
    headOfFrame[2] = length_gb2312 + 3;
    headOfFrame[3] = 0x01;
    headOfFrame[4] = 0x01;

    for (i = 0; i < 5; i++) {
        ecc ^= headOfFrame[i];
        Serial.write(headOfFrame[i]);
    }

    for (i = 0; i < length_gb2312; i++) {
        ecc ^= gb2312Text.charAt(i);
        Serial.write(gb2312Text.charAt(i));
    }

    Serial.write(ecc);
}

void loop() {
    if (!client.connected()) {
        while (!client.connect("ArduinoClient")) {
            delay(1000);
        }
        client.subscribe(mqtt_topic);
    }
    client.loop();
    delay(100);
}